#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <Qmenubar>
#include <qfile>
#include <QFileDialog>
#include <Qsettings>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Reader Ai");
    edit = new QTextEdit;
    setCentralWidget(edit);
    auto *muber = new QMenuBar;
    setMenuWidget(muber);
    auto *file = muber->addMenu("文件");
    auto *tool = muber->addMenu("设置");
    auto *help = muber->addMenu("帮助");
    QAction *open = file->addAction("打开");
    QAction *save = file->addAction("保存");
    file->addAction("另存为");
    help->addAction("关于");
    auto *autoWrap = tool->addAction("自动换行");
    autoWrap->setCheckable(true);
    QSettings *setting=new QSettings("luobo","01_ReaderAi");
    IsAutoWrap=setting->value("IsAutoWrap",true).toBool();
    autoWrap->setChecked(IsAutoWrap);

    //自动换行信号
    connect(autoWrap, &QAction::triggered, [this, setting, autoWrap]()
    {
        IsAutoWrap=!IsAutoWrap;
        if(IsAutoWrap)
        {
            edit->setLineWrapMode(QTextEdit::WidgetWidth);
        }
        else
        {
            edit->setLineWrapMode(QTextEdit::NoWrap);
        }
        setting->setValue("IsAutoWrap",IsAutoWrap);
         autoWrap->setChecked(IsAutoWrap);
    });
       //打开文件
    connect(open, &QAction::triggered, this, &MainWindow::on_open_file);
    //保存文件
    connect(save, &QAction::triggered, this, &MainWindow::on_save_file);
    //另存为文件
    // connect(ui->save, &QAction::triggered, [=]() {));
    // connect(ui->saveAs, &QAction::triggered, [=]() {));
    // connect(ui->setting, &QAction::triggered, [=]() {));
    // connect(ui->action, &QAction::triggered, [=]() {));
    // connect(ui->action, &QAction::triggered, [=]() {));
}

MainWindow::~MainWindow()
{
    delete ui;
}

 void MainWindow::on_open_file(bool checked)
{ 
            //打开文件
            QString fileName = QFileDialog::getOpenFileName(this, "打开文件", "", "文本文件(*.txt)");
            if (!fileName.isEmpty())
            {
                QFile file(fileName);
                if (file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    QTextStream in(&file);
                    QString text = in.readAll();
                    edit->setText(text);
                    file.close();
                    lastPath=QFileInfo(fileName).path();

                }

            }

    }

     void MainWindow::on_save_file(bool checked)
    {
            //保存文件
            QString fileName = QFileDialog::getSaveFileName(this, "保存文件",lastPath, "文本文件(*.txt)");
            if (!fileName.isEmpty())
            {
                QFile file(fileName);
                if (file.open(QIODevice::WriteOnly | QIODevice::Text))
                {
                    QTextStream out(&file);
                    out << edit->toPlainText();
                    file.close();
                }
            }

    }